import Foundation
import SwiftJWT
import ConstantModule

//struct Config {
//     static var share = Config()
//     var secretKey = "" // 替换为实际的密钥
//     var iss = "" // 替换为实际的密钥
//    
//    init() {
//        if App.shared.environment.contains(.test) ||
//            App.shared.environment.contains(.stage) {
//            secretKey = "dae47bcfa9de32273229f939ce1b386c"
//            iss = "apps-agent-5o-stage-test-default"
//        }else{
//            secretKey = "bdb1add9c2901c941068a5ed8a66f8e3"
//            iss = "test001-jwt-20250218"
//        }
//    }
//}

struct MyClaims: Claims {
    var iss: String
    var exp: Date
    var nbf: Date
}

class JwtTokenUtil {

    /// 获取时间戳，模拟根据给定秒数偏移后的时间
    /// - Parameter deltaSeconds: 时间偏移的秒数
    /// - Returns: Date 对象
    private static func getTimestamp(deltaSeconds: Int) -> Date {
        return Date(timeIntervalSinceNow: TimeInterval(deltaSeconds))
    }
    nonisolated(unsafe) static let share: JwtTokenUtil = JwtTokenUtil()
    private var token: String = ""
    /// 生成 JWT Token
    /// - Parameter iss: 签发者
    /// - Returns: JWT 字符串
    class func generateToken() -> String {
        if !JwtTokenUtil.share.token.isEmpty {
            return JwtTokenUtil.share.token
        }
        let claims = MyClaims(
            iss: App.URLConstant.iss,
            exp: getTimestamp(deltaSeconds: 23 * 60 * 60), // 当前时间后推 24 小时
            nbf: getTimestamp(deltaSeconds: -(60 * 60))           // 当前时间前推 10 秒
        )

        var jwt = JWT(claims: claims)
        let jwtSigner = JWTSigner.hs256(key: App.URLConstant.secretKey.data(using: .utf8)!)

        do {
            let token = try jwt.sign(using: jwtSigner)
            JwtTokenUtil.share.token = token
            return token
        } catch {
            print("Error generating token: \(error)")
            return ""
        }
    }

}
